package top.lenjon.lib.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.WebContext;
import top.lenjon.lib.model.MailModel;
import top.lenjon.lib.service.MailService;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.Objects;

/**
 * @Author whz
 * @Date 2020/11/10 09:47
 **/
@Service
@Slf4j
public class MailServiceImpl implements MailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private JavaMailSender mailSender;


    @Value("${mail.fromMail.addr}")
    private String from;


    @Override
    public void sendHtmlMail(MailModel mailModel) {

        LocalDate date = LocalDate.now();
        Context context = new Context();

        //demoMapper.saveTime(date,entity.getRank());
        //demoMapper.saveUser(user,entity.getRank());
// TODO: 2020/11/10
        context.setVariable("url", "");
        context.setVariable("time", date);
        context.setVariable("username", mailModel.getNickname());
        context.setVariable("message", mailModel.getMessage());
        String emailContent = templateEngine.process("emailTemplate", context);
        sendMail(mailModel.getEmail(), "图书馆", emailContent);

    }

    @Override
    @Async
    public void sendRegisterMail(MailModel mailModel) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        //System.out.println(request);
//      HttpServletResponse response=((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        String urlHead = "http://47.100.90.111:9090";
//        System.out.println(path);
//        String urlHead=request.getRequestURL().toString().replace(path, "");
//        System.out.println(urlHead);
        LocalDate date = LocalDate.now();
        Context context = new Context();
        context.setVariable("url", urlHead + "/register/confirm?uuid=" + mailModel.getUuid());
//        context.setVariable("id", mailModel.getId());
        context.setVariable("uuid", mailModel.getUuid());
        context.setVariable("time", date);
        context.setVariable("username", mailModel.getNickname());
        context.setVariable("message", mailModel.getMessage());
        log.debug(context.getVariable("url").toString());
        String emailContent = templateEngine.process("emailTemplate", context);
        sendMail(mailModel.getEmail(), "图书馆", emailContent);

    }


    public void sendMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            logger.info("html邮件发送成功");
        } catch (MessagingException e) {
            logger.error("发送html邮件时发生异常！", e);
        }
    }
}
